import style from './app.module.scss'
import React, { useEffect, useState } from 'react'
import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'
import ProtectedRoute from './starter/ProtectedRoute/ProtectedRoute'
import NotFound from './base/components/NotFound404/notFound'

import MainView from './Views/Main/MainView'

import { AuthView } from './Views/Auth/AuthView'
import { JWT_LS } from './starter/constants'
import { useAppSelector } from './starter/hooks/redux'
import { useLazyCheckTokenQuery } from './starter/api/authApi'
import Layout from './Views/Layout/Layout'

function App() {
  const navigate = useNavigate()
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false)

  const {token} = useAppSelector(state => state.auth)
  const [checkToken,{ data : currentUser, isSuccess: isSuccessCheckUser, isLoading: isLoadingCheckUser, isError: isErrorCheckUser, error }] = useLazyCheckTokenQuery()

  useEffect(() => {
    if (!token) {
      setIsLoggedIn(false)
      navigate('/signin')
    }
    else {
      checkToken(token)
    }
  }, [token])

  useEffect(() => {
    if (isSuccessCheckUser) {
      setIsLoggedIn(true)
      navigate('/')
    }
  }, [isSuccessCheckUser])

  useEffect(() => {
    if (isErrorCheckUser) {
      setIsLoggedIn(false)
      navigate('/signin')
    }
  }, [isErrorCheckUser])

  function onSignOut(): void {
    localStorage.removeItem(JWT_LS)
    setIsLoggedIn(false)
  }


  return (
    <>
      {
        isLoadingCheckUser && <div>
        CHECKING!!!!
        </div>
      }
      {
        !isLoadingCheckUser &&
        <div className={style.page}>
          <Routes>
            <Route path='/' element={
                <Layout/>
              }
            />
            <Route
              path='/main'
              element={
                <ProtectedRoute
                  element={Layout}
                  isLoggedIn={isLoggedIn}
                />
              }
            />
            <Route
              path='/signup'
              element={
                isLoggedIn ? <Navigate to='/' replace /> :
                <AuthView
                  type={'signUp'}
                />
              }
            />
            <Route
              path='/signin'
              element={
                isLoggedIn ? <Navigate to='/' replace /> :
                <AuthView
                  type={'signIn'}
                />
              }
            />
            <Route path='*' element={<NotFound />} />
          </Routes>
        </div>
      }
    </>
  )
}

export default App
